import logging
from datetime import datetime, timedelta
from django.utils import timezone
from django.db import transaction, models
from .models import IndustryKeyword, InsightTask, TechInsight, InsightReference
from celery import shared_task
from django.contrib.auth import get_user_model
from dify.api import run_workflow, parse_workflow_response, DifyAPIError

logger = logging.getLogger(__name__)
User = get_user_model()

def sync_industry_insights():
    """同步行业技术洞察
    每7天执行一次，为每个行业的关键词创建洞察任务
    """
    now = timezone.now()
    
    # 获取需要同步的行业
    industries = IndustryKeyword.objects.filter(
        is_active=True
    ).filter(
        # 首次同步或上次同步时间超过7天
        models.Q(last_sync_at__isnull=True) | 
        models.Q(last_sync_at__lt=now - timedelta(days=7))
    )
    
    for industry in industries:
        try:
            with transaction.atomic():
                # 为每个关键词创建任务
                for keyword in industry.keywords:
                    InsightTask.objects.create(
                        industry=industry.industry,
                        keyword=keyword
                    )
                
                # 更新同步时间
                industry.last_sync_at = now
                industry.save()
                
                logger.info(f"已为行业 {industry.industry} 创建洞察任务")
                
        except Exception as e:
            logger.error(f"创建行业 {industry.industry} 的洞察任务失败: {str(e)}")

def process_insight_tasks():
    """处理技术洞察任务"""
    # 获取待处理的任务
    tasks = InsightTask.objects.filter(
        status='pending'
    ).order_by('created_at')[:10]  # 每次处理10个任务
    
    for task in tasks:
        try:
            # 更新任务状态
            task.status = 'processing'
            task.save()
            
            # 调用生成接口
            response = run_workflow(
                workflow_name="技术洞察",
                inputs={
                    "industry": task.industry,
                    "keyword": task.keyword
                },
                user=str(User.objects.filter(is_superuser=True).first().id)
            )
            
            if response.status_code == 200:
                # 更新任务状态
                task.status = 'completed'
                task.completed_at = timezone.now()
                task.save()
                
                logger.info(f"任务完成 - 行业: {task.industry}, 关键词: {task.keyword}")
            else:
                raise Exception(f"生成失败: {response.data.get('message')}")
                
        except Exception as e:
            logger.error(f"处理任务失败 - 行业: {task.industry}, 关键词: {task.keyword}: {str(e)}")
            task.status = 'failed'
            task.error_message = str(e)
            task.save()

@shared_task
def generate_tech_insights():
    """定时生成技术洞察"""
    try:
        # 获取需要生成洞察的行业和关键词
        industries = IndustryKeyword.objects.filter(is_active=True)
        
        for industry_config in industries:
            for keyword in industry_config.keywords:
                try:
                    # 检查是否已存在
                    if not TechInsight.objects.filter(
                        industry=industry_config.industry,
                        keyword=keyword
                    ).exists():
                        # 生成新的洞察
                        admin_user = User.objects.filter(is_superuser=True).first()
                        if not admin_user:
                            raise Exception("未找到管理员用户")
                            
                        # 调用 Dify API 生成内容
                        response = run_workflow(
                            workflow_name="技术洞察",
                            inputs={
                                "industry": industry_config.industry,
                                "keyword": keyword
                            },
                            user=str(admin_user.id)
                        )
                        
                        content = parse_workflow_response(response)
                        
                        # 创建洞察记录
                        TechInsight.objects.create(
                            title=f"{industry_config.industry}-{keyword}技术洞察",
                            industry=industry_config.industry,
                            keyword=keyword,
                            insight_content=content,
                            user=admin_user
                        )
                        
                except Exception as e:
                    logger.error(f"生成失败 - {industry_config.industry}/{keyword}: {str(e)}")
                    continue
                    
    except Exception as e:
        logger.error(f"批量生成失败: {str(e)}", exc_info=True) 